package com.wsd.smartcarwasher.interceptor;


import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.service.RedisService;
import com.wsd.smartcarwasher.util.RequestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 名称：LogInterceptor <br>
 * 描述：日志拦截器<br>
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {

    private static final Log log = LogFactory.getLog(LogInterceptor.class);

    private static final String key = "logData";

    private static Integer index;

    @Resource
    private RedisService redisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("REQUEST_START_TIME", new Date());

        return true;

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler,
                                Exception ex)
            throws Exception {

        Date start = (Date) request.getAttribute("REQUEST_START_TIME");
        Date end = new Date();
        String logInfo = "本次请求耗时：" + (end.getTime() - start.getTime()) + "毫秒；" + getRequestInfo(request).toString();
        log.info(logInfo);
        saveLogInfo(logInfo);

    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,
                                               HttpServletResponse response,
                                               Object handler)
            throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    /**
     * 主要功能:获取请求详细信息
     * 注意事项:无
     *
     * @param request 请求
     * @return 请求信息
     */
    private StringBuilder getRequestInfo(HttpServletRequest request) {
        StringBuilder reqInfo = new StringBuilder();
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        String urlPath = urlPathHelper.getLookupPathForRequest(request);
        reqInfo.append(" 请求路径=" + urlPath);
        reqInfo.append(" 来源IP=" + RequestUtil.getIpAddrByRequest(request));


        String userName = "";
        try {

            UserInfo sysUser = (UserInfo) SecurityUtils.getSubject().getSession().getAttribute(Global.CURRENT_USER);
            if (sysUser != null) {
                userName = (sysUser.getUsername());
            }

        } catch (Exception e) {

        }
        reqInfo.append(" 操作人=" + (userName));
        reqInfo.append(" 请求参数=" + RequestUtil.getParameters(request).toString());
        return reqInfo;
    }

    //保存日志信息到
    private void saveLogInfo(String logInfo) {
        if (index == null) {
            //获取日志条数
            index = (Integer) redisService.get(key);
        }
        if (index == null) {
            index = 0;
        }
        //缓存日志信息
        redisService.put(key + (++index), logInfo, -1);
        //缓存日志条数
        redisService.put(key, index, -1);
    }
}
